import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface Todo {
  id: number
  text: string
  completed: boolean
}

interface TodoState {
  todos: Todo[]
  editingId: number | null
  inputValue: string
}

const initialState: TodoState = {
  todos: [],
  editingId: null,
  inputValue: '',
}

const todoSlice = createSlice({
  name: 'todo',
  initialState,
  reducers: {
    setInputValue(state, action: PayloadAction<string>) {
      state.inputValue = action.payload
    },
    addTodo(state) {
      if (state.inputValue.trim()) {
        state.todos.push({
          id: Date.now(),
          text: state.inputValue,
          completed: false,
        })
        state.inputValue = ''
      }
    },
    startEditTodo(state, action: PayloadAction<{ id: number; text: string }>) {
      state.editingId = action.payload.id
      state.inputValue = action.payload.text
    },
    editTodo(state) {
      if (state.editingId !== null && state.inputValue.trim()) {
        const todo = state.todos.find(t => t.id === state.editingId)
        if (todo) todo.text = state.inputValue
        state.editingId = null
        state.inputValue = ''
      }
    },
    toggleTodo(state, action: PayloadAction<number>) {
      const todo = state.todos.find(t => t.id === action.payload)
      if (todo) todo.completed = !todo.completed
    },
    deleteTodo(state, action: PayloadAction<number>) {
      state.todos = state.todos.filter(t => t.id !== action.payload)
    },
    clearTodos(state) {
      state.todos = []
    },
    cancelEdit(state) {
      state.editingId = null
      state.inputValue = ''
    },
  },
})

export const {
  setInputValue,
  addTodo,
  startEditTodo,
  editTodo,
  toggleTodo,
  deleteTodo,
  clearTodos,
  cancelEdit,
} = todoSlice.actions
export default todoSlice.reducer
